package project.tool4nat.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import static project.tool4nat.common.Constants.CID_LENGTH;
import static project.tool4nat.common.Constants.TYPE_LENGTH;

public class DataPackEncoder extends MessageToByteEncoder<DataPack> {

    @Override
    protected void encode(ChannelHandlerContext ctx, DataPack dataPack, ByteBuf out) throws Exception {
        int length = TYPE_LENGTH + CID_LENGTH;
        long cid = dataPack.getCid();
        byte[] data = dataPack.getData();
        if (data != null) {
            length += data.length;
        }
        out.writeInt(length);
        out.writeByte(dataPack.getType());
        out.writeLong(cid);
        if (data != null) {
            out.writeBytes(data);
        }
    }

}
